#include <iostream>
#include <memory>
#include <string>
#include <fstream>
#include <unistd.h>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"

using namespace std;

string SuffixToType(const string &suffix)
{
    if (suffix == ".html" || suffix == ".html")
        return "text/html";
    else if (suffix == ".png")
        return "image/png";
    else if (suffix == ".jpg")
        return "image/jpeg";
    else
    {
        return "text/html";
    }
}

string CodetoDesc(int code)
{
    switch (code)
    {
    case 200:
        return "OK";
    case 301:
        return "Moved Permanently";
    case 307:
        return "Temporary Redirect";
    case 403:
        return "Forbidden";
    case 404:
        return "Not Found";
    case 500:
        return "Internal Server Error";
    default:
        return "Unknown";
    }
}

// 处理报文的方法
string HandlerHttpRequest(string &request)
{
    HttpRequest req;
    req.Deserialize(request);
    req.Parse();
    req.DebugHttp();
    int code = 200;

    string content = req.GetFileContent();
    if (content.empty())
    {
        code = 404;
        content = req.Get_404();
    }

    HttpResponse resp;
    resp.SetCode(code);
    resp.SetDesc(CodetoDesc(code));
    resp.MakeStatusLine();
    string content_len_str = "Content-Length: " + to_string(content.size()) + "\r\n";
    resp.AddHeader(content_len_str);
    string content_type_str = "Content-Type: " + SuffixToType(req.Suffix()) + "\r\n"; // 正文的类型
    resp.AddHeader(content_type_str);
    resp.AddContent(content);
    return resp.Serialize();
}

// ./server port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        cout << "Usage: " << argv[0] << "port" << endl;
        return 0;
    }

    uint16_t localport = std::stoi(argv[1]);
    std::unique_ptr<TcpServer> svr(new TcpServer(localport, HandlerHttpRequest));
    svr->Loop();
}